#!/usr/bin/env bash
# 这是一个shell脚本
cd "$(dirname "$0")"
# 脚本只要发生错误，就终止执行。
set -e
# ---------------------------------------------------------------------
# 如果脚本中需要root权限，使用下面的代码更合理。
#SUDO=
#if [ "$UID" != "0" ]; then
#	if [ -e /usr/bin/sudo -o -e /bin/sudo ]; then
#		SUDO=sudo
#	else
#		echo '*** This script requires root privileges.'
#		exit 0
#	fi
#fi
# ---------------------------------------------------------------------
# 但为了脚本里的代码能单独使用，还是内嵌了 sudo 命令。
# if [ `whoami` != "root" ]; then echo "请使用 sudo 执行此脚本！" && exit 1; fi
# ---------------------------------------------------------------------
# 测试网络
echo "正在测试网络，请稍等..."
(ping -c 4 114.114.114.114 && echo "网络没有问题！") || ( echo "网络不通，确保联网后重试！" ; exit 1 )
# if [ $? -ne 0 ]; then
    # echo "网络不通，确保联网后重试！"
    # exit 1
# else
    # echo "网络没有问题！"
# fi
# ---------------------------------------------------------------------
# 备份整个 /etc 目录，并完整保留所有权限。
if [ ! -f ~/.local/etc.tar.xz ] ; then
    echo "正在备份 /etc 目录至 ~/.local/etc.tar.xz"
    mkdir -p ~/.local
    export XZ_OPT="-T0" ; sudo tar caPf ~/.local/etc.tar.xz /etc
    sudo chown "${USER}":"${USER}" ~/.local/etc.tar.xz
    echo "备份 ~/etc.tar.xz 成功！"
fi
# ---------------------------------------------------------------------
sudo timedatectl set-timezone "Asia/Shanghai" && echo "时区设置为东8区成功！"
# 设置时间同步服务器
if [ ! -f /etc/systemd/timesyncd.conf.bak ]; then sudo cp /etc/systemd/timesyncd.conf /etc/systemd/timesyncd.conf.bak; fi
sudo sed -i 's/^#\?NTP=.*$/NTP=cn.pool.ntp.org ntp.aliyun.com time.asia.apple.com time1.cloud.tencent.com/' /etc/systemd/timesyncd.conf
sudo systemctl restart systemd-timesyncd.service
echo "同步系统时间成功！"
# 查看时间设置
timedatectl
# ---------------------------------------------------------------------
# 修改raspbian的系统源
machine=$(uname -m)
# armv7l aarch64 amd64
setup_sources(){
    if [ ! -f /etc/apt/sources.list.bak ]; then sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak; fi
    if [ ! -f /etc/apt/sources.list.d/raspi.list.bak ]; then sudo cp /etc/apt/sources.list.d/raspi.list /etc/apt/sources.list.d/raspi.list.bak; fi
    # 修改raspbian的软件源
    apt_raspi="mirrors.ustc.edu.cn/archive.raspberrypi.org"
    sudo sed -i 's|http://archive.raspberrypi.org|https://'${apt_raspi}'|g' /etc/apt/sources.list.d/raspi.list
    if test "${machine}" = "armv7l" ; then
        # 可选：mirrors.ustc.edu.cn/raspbian  mirrors.tuna.tsinghua.edu.cn/raspbian  mirrors.aliyun.com/raspbian
        apt_source="mirrors.ustc.edu.cn/raspbian"
        # 可选：mirrors.tuna.tsinghua.edu.cn/raspberrypi，阿里云没有这个源
        sudo sed -i 's|http://raspbian.raspberrypi.org|https://'${apt_source}'|g' /etc/apt/sources.list
        echo "设置raspbian的系统源 ${apt_source} 成功！"
    elif test "${machine}" = "aarch64" ; then
      # 推荐直接修改，更直接，而且可以添加非自有软件库。
      cat << "EOF" | sudo tee /etc/apt/sources.list
deb https://mirrors.ustc.edu.cn/debian/ buster main contrib non-free
deb https://mirrors.ustc.edu.cn/debian/ buster-updates main contrib non-free
deb https://mirrors.ustc.edu.cn/debian-security/ buster/updates main contrib non-free
EOF
    fi
    echo "设置APT软件源成功！"
}
setup_sources
# ---------------------------------------------------------------------
setup_testing(){
    # 当Buster还没有进入stable时，设置的testing软件源其实就是Buster。
    if grep "testing main" /etc/apt/sources.list ; then
        echo "已经设置过testing源，无需重复设置！"
    else
        echo "#deb https://mirrors.ustc.edu.cn/raspbian/raspbian/ testing main contrib non-free rpi" | sudo tee -a /etc/apt/sources.list
        echo "设置testing源成功！"
    fi
    # 调低testing源的优先级
    cat << "EOF" | sudo tee /etc/apt/preferences.d/10preferences
Package: *
Pin: release a=testing
Pin-Priority: 400
EOF
}
# 暂时不设置 testing 源
# setup_testing
# ---------------------------------------------------------------------
# 设置命令别名
cat << "EOF" | tee ~/.bash_aliases
# 自定义命令部分
XZ_OPT="-T0"
alias ll='ls -alF'
alias la='ls -A'
alias uu='sudo apt update && sudo apt upgrade'
alias temp="awk -v x=\$(cat /sys/class/thermal/thermal_zone0/temp) 'BEGIN{printf \"%-4.2f C\\n\",x/1000}'"
alias sc="systemctl"
alias jc="journalctl"
function readini(){
    FILENAME=$1; SECTION=$2; KEY=$3
    RESULT=`awk -F ' = ' '/\['$SECTION'\]/{a=1}a==1&&$1~/'$KEY'/{print $2;exit}' $FILENAME`
    echo $RESULT
}
EOF
source "$HOME"/.bashrc
# ---------------------------------------------------------------------
# 修改本地主机名。修改的配置文件为 /etc/hostname
sudo hostnamectl set-hostname raspi
sudo systemctl restart systemd-hostnamed.service
# 修改域名。
# 127.0.0.1 一般为 localhost，表示本地域名，可以用localhost域名访问本机的IP。
# 127.0.1.1 表示的就是真正的本机域名了，使用www服务时，就是外部访问的域名。路由器上识别的名称也是此名称。
# 参考：https://www.debian.org/doc/manuals/debian-reference/ch05.zh-cn.html#_the_hostname_resolution
sudo sed -i 's/^.*127.0.1.1.*$/127.0.1.1       raspi/' /etc/hosts
echo "主机名设置为 raspi 成功！重新登录生效！"
# ---------------------------------------------------------------------
# 设置键盘布局
# localectl list-x11-keymap-layouts
sudo localectl set-keymap "us"
sudo localectl set-x11-keymap "us"
echo "设置为美式键盘成功！"
# ---------------------------------------------------------------------
# 设置wifi国家为中国
if [ ! -f /etc/wpa_supplicant/wpa_supplicant.conf.bak ]; then sudo cp /etc/wpa_supplicant/wpa_supplicant.conf /etc/wpa_supplicant/wpa_supplicant.conf.bak; fi
if ! sudo grep "country=CN" /etc/wpa_supplicant/wpa_supplicant.conf ; then
    echo "country=CN" | sudo tee -a /etc/wpa_supplicant/wpa_supplicant.conf
fi
# 无线网卡应用新的配置
wpa_cli -i wlan0 reconfigure
# ---------------------------------------------------------------------
# 设置ssh免密自动登录
mkdir -p ~/.ssh
cat << "EOF" | tee ~/.ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAQEAnk0RF6kvIBxgZMqZbLoVZVQn8rb9BiLvmkX3fXjh/U8+sNH+ciU269czlBP6WAS1UostgUPzvVKiHJCvx8ng/hi9zE8+dhplnb1xgv8joJPbJgaM0rF6wWfPCTSqKYHcZ23MNBTEK95VhztPMW1gn8CShDSd8oRDasVcEgFK+cpVbWWIIuBARCS5NL1ZOZwOqI5azbtedKBlDM70ncxc4xTd9w7ytgKlPhL2eK2TgHCZXjs+KLlJvEnm0sWo+40fo7enUpj/eUviGlZCpf6eV5HkOk11E10NcIRp3y33qIjfABXrJppbwMjY5VnR3sLSmNFnUA/CULATgAuzy7bw1w== rsa-key-20181203
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDrssFeqo9vOu2Ws67zx7MfH/MAlNOD/s0pg3SHctIxF5rQMVem71c96btzT7PtzHBEevpxsC7roTyYrJAqD3CSMHrPQewJd34mgBQTU9+OzEJ+pQI8kcjqJqn6qQRNO7sPZ1O4s8ar6qLU4yikpBKoRtwiC+zzFYIC6NwnZ4B32yOpM14JHHNFhqfTsIM4qv9GqXvjqmA4A2Cngl/so3C+20wTGXbDAeTMq2vQ5pME0yi24jLG9YL7+5Q+QTHHaTG/gV9NXxVnx8ton9gdtGBFQzciflnECSlWAETsu++93S495EuTBjy/D96oAHEQl1OWfmFL1/IXm/Q4NQ5dpF2V RSA_2018-12-24
EOF
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
sudo systemctl restart ssh
# ---------------------------------------------------------------------
# 虚拟内存文件设置为 1G，如果不设置 dphys 会自动设置。
#if [ ! -f /etc/dphys-swapfile.bak ]; then sudo cp /etc/dphys-swapfile /etc/dphys-swapfile.bak; fi
#sudo sed -i 's/CONF_SWAPSIZE=.*/CONF_SWAPSIZE=1024/' /etc/dphys-swapfile
#sudo systemctl restart dphys-swapfile.service
#free -h
# ---------------------------------------------------------------------
# 进入 vi 编辑后，按 backspace 无法删除，且上下键盘失灵，解决方法
if [ ! -f /etc/vim/vimrc.tiny.bak ]; then sudo cp /etc/vim/vimrc.tiny /etc/vim/vimrc.tiny.bak; fi
sudo sed -i '/^set compatible.*$/a set backspace=2' /etc/vim/vimrc.tiny
sudo sed -i 's/set compatible/set nocompatible/' /etc/vim/vimrc.tiny
# ---------------------------------------------------------------------
# 随系统自动启动systemd用户实例，在会话全部结束时，也不停止用户实例。
sudo loginctl enable-linger "$USER"
# ---------------------------------------------------------------------
# 更新系统
sudo apt-get update && sudo apt-get -y upgrade
# ---------------------------------------------------------------------
setup_python(){
    # 安装测试版 python3、python3-pip
    # sudo apt-get -y install -t testing python3 python3-pip
    sudo apt-get -y install python3-pip

    # 使用国内源，可选：
    # https://mirrors.aliyun.com/pypi/simple
    # https://mirrors.ustc.edu.cn/pypi/web/simple
    # https://pypi.tuna.tsinghua.edu.cn/simple
    pip3 config set global.index-url https://mirrors.ustc.edu.cn/pypi/web/simple
    # 默认 install 加上 --user 参数，以后使用 pip install 就不用每次加 --user 参数。
    pip3 config set global.timeout 120
    pip3 config set install.user true
    #默认为升级
    pip3 config set install.upgrade true
    
    # 更新pip至最新
    python3 -m pip install --user -U pip
    # 加载最新的 pip3、pip 命令
    source "$HOME/.profile"
    
    # 安装常用的库
    pip3 install setuptools wheel
    pip3 install requests
}
setup_python
# ---------------------------------------------------------------------
setup_samba(){
    # 安装samba
    sudo apt-get -y install samba
    # 配置samba
    if [ ! -f /etc/samba/smb.conf.bak ]; then sudo cp /etc/samba/smb.conf /etc/samba/smb.conf.bak; fi
    cat << "EOF" | sudo tee /etc/samba/smb.conf
[global]
    # 局域网工作组
    workgroup = WORKGROUP
    # 定义日志文件的存放位置与名称，参数%m为来访的主机名
    log file = /var/log/samba/log.%m
    # 定义日志文件的最大容量为 50KB
    max log size = 50
    # #定义用户后台的类型，默认为 tdbsam
    passdb backend = tdbsam
    # 允许匿名访问
    map to guest = bad user
    # 启用可以访问软连接，这个要全局设置
#    unix extensions = no
    # 启用可以访问软连接，这2个参数可以局部设置
#    wide links = yes
#    follow symlinks = yes
    # 指定SMB的版本最低为V3版（SMB3），不支持 V1、V2
    client min protocol = SMB3
[homes]
    comment = Home Directories
    browseable = no
    read only = no
    create mask = 0600
    directory mask = 0700
    valid users = %S
[orico]
    comment = Orico移动硬盘
    path = /mnt/sdb1/orico
    guest ok = no
    browseable = no
    writeable = yes
    create mask = 0644
    directory mask = 0755
    # 载入Samba用于回收站功能的模块recycle.so
    vfs object = recycle 
    # 回收站的相对路径，删除的文件会被放入你共享的文件夹下的.trash_samba文件夹中
    # .trash_samba/%U是按登录的用户名分开存放
    recycle:repository = .trash_samba
    # 指定是否按删除时的目录结构存放
    recycle:keeptree = Yes
    # 指定是否区覆盖同名的文件,yes 是不覆盖
    recycle:versions = Yes
    # 指定回收站目录的大小,0是不限制
    recycle:maxsixe = 0
    # 不放入回收站的文件类型
    recycle:exclude = *.tmp|*.mp3
    # 指定覆盖同名文件的文件类型
    recycle:noversions = *.tmp
    # 启用可以访问软连接，这2个参数可以局部设置
#    wide links = yes
#    follow symlinks = yes
[bak]
    comment = 备份目录
    path = /mnt/sdb1/bak
    guest ok = no
    browseable = no
    writeable = yes
    create mask = 0644
    directory mask = 0755
    # 载入Samba用于回收站功能的模块recycle.so
    vfs object = recycle
    # 回收站的相对路径，删除的文件会被放入你共享的文件夹下的.trash_samba文件夹中
    # .trash_samba/%U是按登录的用户名分开存放
    recycle:repository = .trash_samba
    # 指定是否按删除时的目录结构存放
    recycle:keeptree = Yes
    # 指定是否区覆盖同名的文件,yes 是不覆盖
    recycle:versions = Yes
    # 指定回收站目录的大小,0是不限制
    recycle:maxsixe = 0
    # 不放入回收站的文件类型
    recycle:exclude = *.tmp|*.mp3
    # 指定覆盖同名文件的文件类型
    recycle:noversions = *.tmp
EOF
    sudo systemctl restart nmbd
    sudo systemctl restart smbd
    echo "设置samba成功！"
}
setup_samba

# ---------------------------------------------------------------------

setup_syncthing(){
    # 安装 syncthing
    # Add the release PGP keys:
    curl -s https://syncthing.net/release-key.txt | sudo apt-key add -
    # Add the "stable" channel to your APT sources:
    echo "deb https://apt.syncthing.net/ syncthing stable" | sudo tee /etc/apt/sources.list.d/syncthing.list
    sudo apt-get update
    sudo apt-get -y install syncthing
    # 启动一下，让它自动生成配置文件
    syncthing -gui-address="0.0.0.0:8384" -no-browser &
    sleep 20
    pkill syncthing
    sleep 2
    # 修改配置文件
    sed -i 's/127\.0\.0\.1/0\.0\.0\.0/' ~/.config/syncthing/config.xml
    mkdir -p ~/sync
    mkdir -p ~/.config/systemd/user
    cat << "EOF" | tee ~/.config/systemd/user/syncthing.service 
[Unit]
Description=Syncthing - Open Source Continuous File Synchronization
Documentation=man:syncthing(1)
Wants=network.target local-fs.target
After=network.target local-fs.target

[Service]
Nice=10
ExecStart=/usr/bin/syncthing -no-browser -no-restart -logflags=0
Restart=on-failure
SuccessExitStatus=3 4
RestartForceExitStatus=3 4

# Hardening
SystemCallArchitectures=native
MemoryDenyWriteExecute=true
NoNewPrivileges=true

[Install]
WantedBy=default.target
EOF
    systemctl --user enable syncthing.service
    systemctl --user start syncthing.service
    echo "配置syncthing成功！"
}
setup_syncthing

# ---------------------------------------------------------------------
setup_aria2(){
    # 安装最新版的aria2 -t testing
    sudo apt-get -y install aria2
    mkdir -p ~/.config/aria2
    touch ~/.config/aria2/aria2.session
    cat << EOF | tee ~/.config/aria2/aria2.conf 
# Auto generated file, changes to this file will lost.
## '#'开头为注释内容, 选项都有相应的注释说明, 根据需要修改 ##
## 被注释的选项填写的是默认值, 建议在需要修改时再取消注释  ##

## 文件保存相关 ##
# 文件的保存路径(可使用绝对路径或相对路径), 默认: 当前启动位置
dir=$HOME/Download
# 断点续传
continue=true
# 启用磁盘缓存, 0为禁用缓存, 需1.16以上版本, 默认:16M
#disk-cache=32M
# 文件预分配方式, 能有效降低磁盘碎片, 默认:prealloc
# NTFS(MinGW build only)、ext4建议使用falloc
file-allocation=falloc
# 最大同时下载任务数, 运行时可修改, 默认:5
max-concurrent-downloads=20
# Make aria2 quiet (no console output). Default: false
#quiet=true


## 进度保存相关 ##
# 从会话文件中读取下载任务
input-file=$HOME/.config/aria2/aria2.session
# 在Aria2退出时保存 错误/未完成 的下载任务到会话文件
save-session=$HOME/.config/aria2/aria2.session
# 定时保存会话, 0为退出时才保存, 需1.16.1以上版本, 默认:0
save-session-interval=60

## RPC相关设置 ##
# 启用RPC, 默认:false
enable-rpc=true
# RPC监听端口, 端口被占用时可以修改, 默认:6800
rpc-listen-port=6800
# 允许所有来源, 默认:false
rpc-allow-origin-all=true
# 允许从外部访问, 默认:false
rpc-listen-all=true
# 是否启用 RPC 服务的 SSL/TLS 加密,
# 启用加密后 RPC 服务需要使用 https 或者 wss 协议连接
#rpc-secure=true
# 在 RPC 服务中启用 SSL/TLS 加密时的证书文件,
# 使用 PEM 格式时，您必须通过 --rpc-private-key 指定私钥
#rpc-certificate=$HOME/.config/aria2/server.crt
# 在 RPC 服务中启用 SSL/TLS 加密时的私钥文件
#rpc-private-key=/$HOME/.config/aria2/server.key

## BT/PT下载相关 ##
# 打开DHT功能, PT需要禁用, 默认:true
enable-dht=true
dht-file-path=$HOME/.config/aria2/dht.dat
# 打开IPv6 DHT功能, PT需要禁用
enable-dht6=true
dht-file-path6=$HOME/.config/aria2/dht6.dat
# 分享率1.0，默认值。
seed-ratio=1
# 做种30分钟。
seed-time=30
# 本地节点查找, PT需要禁用, 默认:false
bt-enable-lpd=true
# 种子交换, PT需要禁用, 默认:true
enable-peer-exchange=true
# 当下载的是一个种子(以.torrent结尾)时, 自动开始BT任务, 默认:true
follow-torrent=true
# 客户端伪装, PT需要
peer-id-prefix=-TR2940-
user-agent=Transmission/2.94

bt-tracker=udp://tracker.coppersurfer.tk:6969/announce,udp://tracker.open-internet.nl:6969/announce,udp://tracker.leechers-paradise.org:6969/announce,udp://tracker.opentrackr.org:1337/announce,udp://tracker.internetwarriors.net:1337/announce,udp://9.rarbg.to:2710/announce,udp://9.rarbg.me:2710/announce,udp://tracker.openbittorrent.com:80/announce,http://tracker3.itzmx.com:6961/announce,http://tracker1.itzmx.com:8080/announce,udp://exodus.desync.com:6969/announce,udp://tracker.torrent.eu.org:451/announce,udp://tracker.tiny-vps.com:6969/announce,udp://retracker.lanta-net.ru:2710/announce,udp://bt.xxx-tracker.com:2710/announce,udp://tracker.cyberia.is:6969/announce,udp://open.demonii.si:1337/announce,http://tracker2.itzmx.com:6961/announce,udp://tracker4.itzmx.com:2710/announce,http://open.acgnxtracker.com:80/announce,http://tr.cili001.com:8070/announce
EOF
    chmod 600 ~/.config/aria2/aria2.conf
    # 创建服务
    mkdir -p ~/.config/systemd/user
    cat << EOF | tee ~/.config/systemd/user/aria2.service
[Unit]
Description=aria2 is a lightweight multi-protocol & multi-source command-line download utility
Documentation=man:aria2c(1)
Wants=network.target local-fs.target
After=network.target local-fs.target

[Service]
Type=idle
ExecStart=/usr/bin/aria2c --conf-path=$HOME/.config/aria2/aria2.conf
Restart=on-failure

[Install]
WantedBy=default.target
EOF
    systemctl --user enable aria2.service
    systemctl --user start aria2.service
    echo "配置aria2成功！"
}
setup_aria2

# ---------------------------------------------------------------------
# 启用硬盘休眠，自动判定armhf、arm64版本
#machine=`uname -m`
#if test $machine = "armv7l" ; then
#	version="armhf"
#elif test $machine = "aarch64" ; then
#	version="arm64"	
#else
#	version="armhf"
#fi
#echo ${version}
#cd ~
#wget https://gitee.com/kisa747/kisa747/blob/master/data/hd-idle_1.05_${version}.deb
#sudo dpkg -i hd-idle_1.05_${version}.deb
#rm hd-idle_1.05_${version}.deb
#if [ ! -f /etc/default/hd-idle.bak ]; then sudo cp /etc/default/hd-idle /etc/default/hd-idle.bak; fi
#cat << "EOF" | sudo tee /etc/default/hd-idle
# 启用hd-idle
#START_HD_IDLE=true
# 调整空闲时间为 5 分钟 (60 秒 * 5=300)，设备为sdb
#HD_IDLE_OPTS="-i 0 -a sdb -i 300 -l /var/log/hd-idle.log"
#EOF
# 重启服务、查看服务
#sudo systemctl restart hd-idle.service
# 检查 hd-idle 状态
#systemctl status hd-idle.service -l --no-pager

# ---------------------------------------------------------------------
# 安装远程控制
#sudo apt-get -y install xrdp
# ---------------------------------------------------------------------
# 树莓派上有不少的硬件，如WiFi适配器、蓝牙适配器等等。这些硬件都有特定的固件支持。有时候树莓派安装的是比较旧的固件，可能会带来一些问题。可以从命令行更新固件：
# 参考：https://www.raspberrypi.org/documentation/faqs/#pi-software
# Unless using it is recommended by a Raspberry Pi engineer, you should not use  rpi-update. It updates to the very, very latest test firmware and kernel software, which may not work correctly under all circumstances.
# sudo rpi-update
# 移除孤立的软件
sudo apt-get -y autoremove
# 清理已下载的软件包
sudo apt-get -y clean
# ---------------------------------------------------------------------
# 设置中文 locale
if [ ! -f /etc/locale.gen.bak ]; then sudo cp /etc/locale.gen /etc/locale.gen.bak; fi
cat << "EOF" | sudo tee /etc/locale.gen
en_US.UTF-8 UTF-8
zh_CN.UTF-8 UTF-8
EOF
sudo locale-gen
# Debian 下，set-locale 命令修改的文件是 /etc/default/locale
sudo localectl set-locale LANG="zh_CN.UTF-8" LANGUAGE="zh_CN:zh:en_US:en"
sudo update-locale
sudo systemctl restart systemd-localed.service
echo "设置中文 locale 成功！"
# locale 设置后重启生效，所以放到最后执行
# ---------------------------------------------------------------------
echo "已经全部设置完成，建议 sudo reboot 重启一下系统！"
exit 0
